package cn.conac.rc.ofs.service;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.ofs.entity.OrgsApprovalEntity;
import cn.conac.rc.ofs.repository.OrgsApprovalRepository;
import cn.conac.rc.ofs.vo.OrgsApprovalVo;

@Service
public class OrgsApprovalService extends GenericService<OrgsApprovalEntity, String> {

	@Autowired
	private OrgsApprovalRepository repository;
	
	/**
	 * 计数查询
	 * @param vo
	 * @return 计数结果
	 */
	public long count(OrgsApprovalVo vo){
		return super.count(this.createCriteria(vo));
	}

	/**
	 * 动态查询，分页，排序查询
	 * @param vo
	 * @return Page
	 * @throws Exception
	 */
	public Page<OrgsApprovalEntity> list(OrgsApprovalVo vo) throws Exception {
		try {
			Sort sort = new Sort(Direction.DESC, "appDate");
			Pageable pageable = new PageRequest(vo.getPage(), vo.getSize(), sort);
			Criteria<OrgsApprovalEntity> dc = this.createCriteria(vo);
			return repository.findAll(dc, pageable);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 动态查询条件
	 * @param param
	 * @return Criteria
	 */
	private Criteria<OrgsApprovalEntity> createCriteria(OrgsApprovalVo param) {
		Criteria<OrgsApprovalEntity> dc = new Criteria<OrgsApprovalEntity>();
		// 地区ID
		if(param.getAreaIds()!=null && param.getAreaIds().size() != 0){
			dc.add(Restrictions.in("areaId", param.getAreaIds(), true));
		}
		// 批文号/名称
		if(StringUtils.isNotBlank(param.getAppNumOrName())){
			dc.add(Restrictions.or(Restrictions.QLike("name", param.getAppNumOrName(), true),
					Restrictions.QLike("appNum", param.getAppNumOrName(), true)));
		}
		// 批文时间Start
		if(param.getAppDateStart() != null){
			dc.add(Restrictions.gte("appDate", param.getAppDateStart(), true));
		}
		// 批文时间End
		if(param.getAppDateEnd() != null){
			dc.add(Restrictions.lte("appDate", param.getAppDateEnd(), true));
		}

		return dc;
	}

}
